package vikaa.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import vikaa.bean.WeiboFriend;
import vikaa.timelinepackage.Timeline;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.ValueClass;
import vikaa.wowo.R;
import vikaa.wowo.cache.InvitorSqlStoragePrivate;
import vikaa.wowo.cache.UserInfoSharePreference;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WowoCreate4 extends Activity{
	private TextView titleTv;
	private LinearLayout backBtn;
	private ImageView submitBtn;
	private EditText inviteEdt;
	private String members;
	private String state;
	private ArrayList<WeiboFriend> mList = new ArrayList<WeiboFriend>();
	private String space_id;
	private String spacename;
	public static boolean inviteflag = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wowo_create4);
		initview();
	}
	public void initview(){
		Intent i = getIntent();
		state = i.getExtras().getString("state");
		spacename = i.getExtras().getString("name");
		titleTv = (TextView)findViewById(R.id.titleTv);
		titleTv.setText(spacename);
		mList = InvitorSqlStoragePrivate.getChoosedinSql(WowoCreate4.this);
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(inviteflag){
					DialogService.showProgressDialog(WowoCreate4.this, getString(R.string.inviting));
					new WowoInviteThread(Timeline.space_id, convert2Json(), UserInfoSharePreference.getNickname(getApplicationContext())+""+getString(R.string.invite_letter_content)).start();
				}
				else{
					DialogService.showProgressDialog(WowoCreate4.this, getString(R.string.create_wowo));
					new WowoCreateThread().start();
				}
			}
		});
		inviteEdt = (EditText)findViewById(R.id.inviteEdt);
		inviteEdt.setText(UserInfoSharePreference.getNickname(getApplicationContext())+""+getString(R.string.invite_letter_content));
		inviteEdt.setSelection(inviteEdt.length());
	}
	public String convert2Json(){
		String members = "[";
		for(int i=0;i<mList.size()-1;i++){
			members += mList.get(i).toString() +","; 
		}
		members = members + mList.get(mList.size()-1).toString() + "]";
		return members;
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case 0:
				space_id = (String)msg.obj;
				break;
			case 1:
				space_id = (String)msg.obj;
				members = convert2Json();
				if(members.length() >10 )
					new WowoInviteThread(space_id, convert2Json(), inviteEdt.getText().toString()).start();
				break;
			case 2:
				/*if(phone.length() > 10){
		              Intent intent = new Intent(Intent.ACTION_VIEW);  
		              intent.putExtra("address", phone);  
		              intent.putExtra("sms_body", inviteEdt.getText().toString());  
		              intent.setType("vnd.android-dir/mms-sms");  
		              startActivity(intent); 	
				}*/
				DialogService.closeProgressDialog();
				if(!inviteflag){
					WowoCreate3.isfinish=true;
					Mywowo.isrefresh = true;
					Intent intent = new  Intent(WowoCreate4.this,Timeline.class);
					intent.putExtra("sid", space_id);
					intent.putExtra("role", String.valueOf(ValueClass.ROLE_CREATOR));
					intent.putExtra("count", "0");
					intent.putExtra("spacename", spacename);
					intent.putExtra("cover", "");
					intent.putExtra("credits", "0");
					intent.putExtra("member", "0");
					intent.putExtra("host", "1");
					intent.putExtra("state", state);
					startActivity(intent);
					Toast.makeText(getApplicationContext(), "创建窝窝成功", Toast.LENGTH_SHORT).show();
					finish();
				}else{
					//WowoCreate3.isfinish=true;
					WeiboFriendChoose.wc.finish();
					Mywowo.isrefresh = true;
					finish();
				}
				break;
			case 3://create wowo fail
				DialogService.closeProgressDialog();
				if(msg.obj != null){
					Toast toast = new Toast(WowoCreate4.this);
                	toast = Toast.makeText(getApplicationContext(), getString(R.string.create_wowo_fail) + "" + (String)msg.obj, Toast.LENGTH_SHORT);
                	toast.setGravity(Gravity.CENTER, 0, -60);
                	toast.show();
				}
				break;
			case 4://invite fail
				DialogService.closeProgressDialog();
				Toast.makeText(WowoCreate4.this, getString(R.string.invite_fail)  , Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	class WowoCreateThread extends Thread{
    	boolean isrun = true;
    	@Override
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("spacename", titleTv.getText().toString());
    			map.put("state", state);
    			String url = HttpUtil.BASE_URL + "space/create";
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
					String result = jsonObj.getString("result");
					if(result.equals("1")){
						String space_id = jsonObj.getJSONObject("info").getString("space_id");
						Message msg = mhandler.obtainMessage(1);
						msg.obj = space_id;
						mhandler.sendMessage(msg);
					}else if(result.equals("0")){
						String space = jsonObj.getJSONObject("info").getString("space");
						Message msg = mhandler.obtainMessage(3);
						msg.obj=space;
						mhandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	class WowoInviteThread extends Thread{
    	boolean isrun = true;
    	private String space_id;
    	private String members;
    	private String message;
    	public WowoInviteThread(String space_id, String members, String message) {
			super();
			this.space_id = space_id;
			this.members = members;
			this.message = message;
		}
		@Override
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("space_id", space_id);
    			map.put("members", members);
    			map.put("message", message);
    			String url = HttpUtil.BASE_URL + "space/invite";
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
					String result = jsonObj.getString("result");
					if(result.equals("1")){
						Message msg = mhandler.obtainMessage(2);
						mhandler.sendMessage(msg);
					}else{
						Message msg = mhandler.obtainMessage(4);
						mhandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
}
